from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from day9.settings import MEDIA_ROOT, MEDIA_URL
import uuid
from app1.models import User


# Create your views here.
def index(request):
    return HttpResponse('app4')


class Image(View):
    def get(self, request):
        """
        跳转页面
        :param request:
        :return:
        """
        inof = User.objects.all()
        return render(request, 'image.html', locals())

    def post(self, request):
        image = request.FILES.get('b')
        name = request.POST.get('user')
        print(name)
        # 随机生成 图片的名字

        if str(image.name).endswith('jpg') or str(image.name).endswith('png'):
            if len(image) <= 200*1024:
                image_name = str(uuid.uuid1()) + '.png'
                # 拼接路径
                # 生成随机字符串作为图片的名字
                img_name = str(uuid.uuid1()) + '.png'
                # pinjie 图片保存地址
                img_path = MEDIA_ROOT + '/user/' + img_name
                print(img_path)
                # 下载图片
                with open(img_path, 'wb') as f:
                    for x in image.chunks():
                        f.write(x)
                # 保存到数据库
                User.objects.create_user(
                    username=name,
                    password='123456',
                    image=MEDIA_URL + '/user/' + img_name
                )
                return HttpResponse('添加成功')
            else:
                return HttpResponse('超大了')
        else:
            return HttpResponse('不支持这种格式')
